package com.pw.study.flink.timer;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class TimerTime {

    public static void main(String[] args) {
        dealTimer1();
    }

    private static void dealTimer1() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop111", 9999).map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] data = value.split(" ");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            }
        });

        timer1(stream);

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //时间定时器
    private static void timer1(SingleOutputStreamOperator<WaterSensor> stream) {
        stream.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor sensor, Context ctx, Collector<String> out) throws Exception {
                System.out.println("process............" + sensor);
                //
                long ts = System.currentTimeMillis() + 5000;
                //水位大于30，开始启动定时器
                if (sensor.getVc() > 30) {
                    ctx.timerService().registerProcessingTimeTimer(ts);
                }
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                out.collect(ctx.getCurrentKey() + "...." + timestamp + "传感器检测到水位超过20, 红色预警...");
            }
        }).print();
    }
}
